package com.snail.app.config.service;

import com.snail.app.config.entity.DbConfigDatabase;
import com.snail.app.config.rep.DbConfigDatabaseRep;
import com.snail.common.entity.Page;
import com.snail.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class DbConfigDatabaseService {
    @Autowired
    private DbConfigDatabaseRep dbConfigDatabaseRep;

    public Page pageBySql(Page page, Map<String, Object> params) {
        StringBuilder sql = new StringBuilder();
        sql.append("select * " +
                " from db_config_database db" +
                " where flag=0 ");
        if (!StringUtil.isEmpty(params.get("keyword"))) {
            sql.append(" and name like '%" + params.get("keyword") + "%'");
        }
        return dbConfigDatabaseRep.execSqlPage(page, sql.toString());
    }

    public List<DbConfigDatabase> list() {
        return dbConfigDatabaseRep.execHql("from DbConfigDatabase where flag=0 ");
    }

    /**
     * 需要同步数据的配置信息
     */
    public List<DbConfigDatabase> listSync() {
        return dbConfigDatabaseRep.execHql("from DbConfigDatabase where purpose is not null and purpose!='' and flag=0 ");
    }


    public List<DbConfigDatabase> list(Map<String, Object> params) {
        StringBuilder hql = new StringBuilder("from DbConfigDatabase where flag=0 ");
        if (!StringUtil.isEmpty(params.get("purpose"))) {
            hql.append(" and purpose = " + params.get("purpose"));
        }
        if (!StringUtil.isEmpty(params.get("ip"))) {
            hql.append(" and ip='" + params.get("ip") + "'");
        }
        return dbConfigDatabaseRep.execHql(hql.toString());
    }


    public DbConfigDatabase getById(String id) {
        Optional optional = dbConfigDatabaseRep.findById(id);
        if (optional.isPresent()) {
            return (DbConfigDatabase) optional.get();
        }
        return null;
    }

    public void save(DbConfigDatabase entity) {
        if (entity.getId() == null) {
            entity.setState(0);
            entity.setFlag(0);
        }
        dbConfigDatabaseRep.save(entity);
    }

    public void del(String id) {
        dbConfigDatabaseRep.deleteById(id);
    }
}
